package com.lagou.edu.server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;
import java.util.concurrent.*;

/**
 * @author 胡益文
 * @since 2021/10/13 15:43
 */
public class Service extends LifecycleBase {
    private int port=8080;
    private ThreadPoolExecutor threadPoolExecutor;
    private Mapper mapper;

    public Service(int port, ThreadPoolExecutor threadPoolExecutor, Mapper mapper) {
        this.port = port;
        this.threadPoolExecutor = threadPoolExecutor;
        this.mapper = mapper;
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    @Override
    protected void initInternal() throws Exception {
        for (Map.Entry<String, Mapper.MappedHost> MappedHostEntry : mapper.hosts.entrySet()) {
            for (Map.Entry<String, Mapper.MappedContext> MappedContextEntry : MappedHostEntry.getValue().contexts.entrySet()) {
                MappedContextEntry.getValue().object.init();
            }
        }
    }

    @Override
    protected void startInternal() throws Exception {
        // 开启socket端口服务
        for (Map.Entry<String, Mapper.MappedHost> MappedHostEntry : mapper.hosts.entrySet()) {
            for (Map.Entry<String, Mapper.MappedContext> MappedContextEntry : MappedHostEntry.getValue().contexts.entrySet()) {
                MappedContextEntry.getValue().object.start();
                for (Map.Entry<String, Mapper.MappedWrapper> MappedWrapperEntry : MappedContextEntry.getValue().wrappers.entrySet()) {
                    MappedWrapperEntry.getValue().object.start();
                }
            }
        }
        ServerSocket serverSocket = new ServerSocket(port);
        while (true){
            Socket accept = serverSocket.accept();
            //此处的HttpServletProcessor充当processor本身以及coyoteAdapter以及Engine的作用
            HttpServletProcessor httpServletProcessor = new HttpServletProcessor(accept, mapper);
            threadPoolExecutor.execute(httpServletProcessor);
        }

    }
}
